package com.shunli.cterminal.strategy;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.shunli.cterminal.enums.ConditionTypeEnum;
import com.shunli.cterminal.model.dto.PolicyPriceJsonDTO;
import com.shunli.cterminal.model.dto.TrafficPolicyStrategyDTO;
import com.shunli.cterminal.model.res.SystemTrafficPolicyVO;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 价格策略
 * </p>
 *
 * @author daodao
 * @since 2025-04-25 15:21
 */
@Component
public class PriceStrategy implements Strategy {


    /**
     * 获取条件类型  ConditionTypeEnum
     *
     * @return
     */
    @Override
    public String getConditionTypeEnum() {
        return ConditionTypeEnum.AND.getCode();
    }

    /**
     * 执行策略 结果
     *
     * @param beforeResult 上一个规则过滤后的结果
     * @return String
     */
    @Override
    public Set<SystemTrafficPolicyVO> parse(Set<SystemTrafficPolicyVO> beforeResult, TrafficPolicyStrategyDTO trafficPolicyStrategyDTO) {
        if (CollectionUtil.isEmpty(beforeResult)) {
            return null;
        }
        beforeResult = beforeResult.stream()
                .filter(systemTrafficPolicyVO -> {
                    if (ObjectUtil.isNull(systemTrafficPolicyVO.getPriceJsonDTO())) {
                        return false;
                    }

                    for (PolicyPriceJsonDTO.PolicyPriceInterval policyPriceInterval : systemTrafficPolicyVO.getPriceJsonDTO().getPriceIntervalList()) {
                        BigDecimal targetStartPrice = policyPriceInterval.getStartPrice();
                        BigDecimal targetEndPrice = policyPriceInterval.getEndPrice();
                        boolean isInRangeStartPrice = (NumberUtil.isGreaterOrEqual(trafficPolicyStrategyDTO.getRealAmount(), targetStartPrice) && NumberUtil.isLess(trafficPolicyStrategyDTO.getRealAmount(), targetEndPrice));
                        if (isInRangeStartPrice) {
                            return true;
                        }
                    }
                    return false;
                })
                .collect(Collectors.toSet());
        return beforeResult;
    }
}
